package com.yipao.wx.service;

import com.alibaba.fastjson.JSONObject;
import com.yipao.core.constant.GlobalConstant;
import com.yipao.core.mqtt.service.MqttSendService;
import com.yipao.core.mqtt.vo.MqttSendVo;
import com.yipao.db.domain.Order;
import com.yipao.db.domain.order.OrderGoods;
import com.yipao.db.service.devinfo.DevInfoService;
import com.yipao.db.service.goods.GoodsFormulaService;
import com.yipao.db.service.order.OrderGoodsService;
import com.yipao.db.service.order.OrderService;
import com.yipao.wx.config.MobileProperties;
import com.yipao.wx.vo.mqtt.MqttSendMakeVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * 移动端发送mqtt封装对象
 *
 * @author tianhao
 * @date 2020/6/9 0:31
 **/
@Service
@Slf4j
public class MobileMqttSendService {

    @Resource
    private OrderService orderService;
    @Resource
    private DevInfoService devInfoService;
    @Resource
    private OrderGoodsService orderGoodsService;
    @Resource
    private GoodsFormulaService goodsFormulaService;
    @Resource
    private MqttSendService mqttSendService;
    @Resource
    private MobileProperties mobileProperties;

    /**
     * 订单支付成功,发送开始制作
     *
     * @param orderId 订单表id
     */
    public void sendOrderPaySuccess(Integer orderId) {
        try {
            Order order = orderService.findById(orderId);
            // 查询设备的imei
            String imei = devInfoService.getImeiById(order.getDevId());
            // 查询产品的配方
            // [{"code":"sweet","devParam":"ae","id":3,"unitName":"标准","value":"10"},{"code":"temp","devParam":"a","id":1,"unitName":"热饮","value":"202"},{"code":"temp","devParam":"4","id":2,"unitName":"冷饮","value":"10"}]
            List<OrderGoods> goods = orderGoodsService.findByGid(orderId);
            List<MqttSendMakeVo> list = new ArrayList<>();
            MqttSendMakeVo vo;
            JSONObject material;
            for (OrderGoods good : goods) {
                vo = new MqttSendMakeVo();
                material = new JSONObject();
                // 查询配方的设备参数
                material.put("devParam", goodsFormulaService.queryMaterialDevParamByFormulaId(good.getFormulaId()));
                vo.setMaterial(material);
                vo.setAttr(good.getFormulaAttrJson());
                list.add(vo);
            }
            mqttSendService.send(mobileProperties.getMqttUrl(), new MqttSendVo(imei, 1, GlobalConstant.AndroidOt.START_MAKE, list));
        } catch (Exception e) {
            log.error("mqtt发送<开始制作>,处理异常", e);
        }
    }
}
